package session

import (
	"errors"
	"sync"
)

// memorySession对象  单个session
type MemorySession struct {
	sessionId string
	data map[string]interface{} // 存k-v
	rwlock sync.RWMutex   // 读写锁
}

// 构造函数
func NewMemmorySession(id string) *MemorySession  {
	return &MemorySession{
		sessionId: id,
		data:      make(map[string]interface{}, 16),
	}
}

func (m *MemorySession)Set(Key string, Value interface{}) (err error)  {
	// 加锁
	m.rwlock.Lock()
	// 释放锁
	defer m.rwlock.Unlock()
	// 设置值
	m.data[Key] = Value
	return
}
func (m *MemorySession)Get(Key string) (value interface{}, err error)  {
	// 加锁
	m.rwlock.Lock()
	// 释放锁
	defer m.rwlock.Unlock()
	// 取值
	value, ok := m.data[Key]
	if !ok{
		err = errors.New("key not exists in session")
	}
	return value, err
}
func (m *MemorySession)Del(Key string) (err error)  {
	// 加锁
	m.rwlock.Lock()
	// 释放锁
	defer m.rwlock.Unlock()
	// 删除
	delete(m.data, Key)
	return
}
func (m *MemorySession)Save() (err error)  {
	return
}